/*
 * @Descripttion: 
 * @version: 
 * @Author: turingchang
 * @Date: 2020-08-28 16:08:51
 * @LastEditors: turingchang
 * @LastEditTime: 2020-09-12 16:22:44
 */

const Service = require('egg').Service;

class HomeService extends Service {    

    async login(login_user) {
        var data ={
            msg:'',
            data:{}
        };
        var user ={};
        var token ='';
        var expire ='';      
        var menu =null;

        const admin = await this.ctx.model.Admin.Admin.findOne({
            attributes: { exclude: ['delete_time','roleId']},
            include: {
                model: this.ctx.app.model.Admin.Role,
                include: {
                    model: this.ctx.app.model.Admin.Permission,                    
                },
                where:{
                    status:this.ctx.app.enums.status.normal.value
                },
            },
            where:{
                // id:2,
                name:login_user.name,
                password:login_user.password,
                status:this.ctx.app.enums.status.normal.value
            }
        });
        if(this.ctx.app.utils.validator.isNull(admin)){
            data.msg ='用户名或密码错误';
            return data;
        }        
        expire =eval(this.app.config.jwt.expire)*1;
        token = this.ctx.getToken({
            id:admin.id,
            name:admin.name
        });        
        if(this.ctx.app.utils.validator.isNull(token)){
            data.msg ='系统异常，登录失败';
            return data;
        }
        user =admin;
        user.setDataValue( 'token', token );
        user.setDataValue( 'token_expire', expire );
        //登录成功，开始构建前端权限树
        //获取页面权限及操作权限
        await this.formatAntRolePermissions(user);        
        
        //处理在线状态及个人pkey
        admin.online_status =this.ctx.app.enums.online_status.online.value;
        admin.last_login_ip =this.ctx.ip;
        admin.last_login_time =this.ctx.app.utils.time.getTimeSpan();
        admin.pkey =this.ctx.app.utils.generator.getKey();
        // console.log(admin);
        await admin.save();
        this.ctx.user =admin;
        if(this.ctx.app.utils.validator.isNull(user.role.permissions)){
            data.msg ='很抱歉，您无权访问系统';
            return data;
        }    
        data.data =user;    
        return data;
    }

    async get(id) {
        const user = await this.ctx.model.Admin.Admin.findByPk(id,{
            include: {
                model: this.ctx.app.model.Admin.Role
            }
        });
        return user;
    }
    async create(admin) {
        const res = await this.ctx.model.Admin.Admin.create(admin);
        return res;
    }

    /**
     * 获取权限结构
     * @param {*} admin 
     */
    async getPermissions(admin){
        var data =[];
        var operations ={};
        var permission={};  //菜单权限,包含child操作权限
        var operation=[];   //按钮操作权限
        if(this.ctx.app.utils.validator.isNull(admin)){
            return data;
        }   
        const permissions =admin.role.permissions;
        if(this.ctx.app.utils.validator.isNull(permissions)){
            return data;
        }
        //从权限数组中筛选menu       
        const menu = permissions.filter(item => item.type == this.ctx.app.enums.permission_type.menu.value && item.show == this.ctx.app.enums.show_status.show.value)
        //从权限数组中筛选button操作权限        
        //前端所需结构
        // permission = {
        //     id: 'form',                                    //权限ID
        //     operation: ['add', 'delete', 'edit', 'close']  //权限下的操作权限
        // }       
        for (const item of menu){
            permission={};
            operation =[];
            operations={}; 
            permission.id =item.key;              
            operations =permissions.filter(li => li.type == this.ctx.app.enums.permission_type.action.value && li.pid ==item.id && item.show == this.ctx.app.enums.show_status.show.value);
            for (const op of operations){
                operation.push(op.key);
            }  
            permission.operation = operation;    
            data.push(permission);
        }
        return data;
    }

    async formatAntRolePermissions(admin){
        var data =[];
        var operations ={};
        var permission={};  //菜单权限,包含child操作权限
        var operation=[];   //按钮操作权限
        var action ={};
        var actions =[];
        if(this.ctx.app.utils.validator.isNull(admin)){
            return admin;
        }   
        if(this.ctx.app.utils.validator.isNull(admin.role)){
            return admin;
        }        
        admin.setDataValue( 'role_key', admin.role.key );
        const permissions =admin.role.permissions;
        if(this.ctx.app.utils.validator.isNull(permissions)){
            return admin;
        }
        //从权限数组中筛选menu       
        const menu = permissions.filter(item => item.type == this.ctx.app.enums.permission_type.menu.value && item.show == this.ctx.app.enums.show_status.show.value)
        admin.role.setDataValue( 'permissions', menu );
        admin.role.setDataValue( 'permissionList', [] );
        //从权限数组中筛选action操作权限  
        for (const item of admin.role.permissions){
            actions =[];           
            operations =permissions.filter(li => li.type == this.ctx.app.enums.permission_type.action.value && li.pid ==item.id && item.show == this.ctx.app.enums.show_status.show.value);
            for (const op of operations){
                action ={
                    action:op.key,
                    describe:op.name
                };
                actions.push(action);               
            }  
            item.setDataValue( 'action_set', actions );
            item.setDataValue( 'actions', JSON.stringify(actions));
            item.setDataValue( 'role_id', admin.role.id );
            item.setDataValue( 'role_key', admin.role.key );
            item.setDataValue( 'actionList', null );
        }
        
        return admin;
    }

    async getMenu(permissions,pid){
        // var admin =this.ctx.user;
        var data =[];
        var menu ={};
        var menus = await this.getNode(permissions,pid);
        menu={
            router: '/', 
            children:menus    
        }
        data.push(menu);
        return data;
    }

    async getNode(permissions,pid){
        if(this.ctx.app.utils.validator.isNull(pid)){
            pid =0;
        }
        var data =[];
        var menu ={};
        var children =[];
        var obj =permissions.filter(item => item.pid == pid && item.type == this.ctx.app.enums.permission_type.menu.value && item.show == this.ctx.app.enums.show_status.show.value);
        for (const item of obj){
            menu ={};
            menu.router =item.key;
            menu.key =item.key;
            menu.name =item.name;
            menu.icon =item.icon;
            menu.path =item.url;
            menu.authority ={
                permission:item.key
            };
            menu.children=await this.getNode(permissions,item.id);
            data.push(menu);
        }
        return data;
    }

    async menu(){
        var router =[];
        const admin = await this.ctx.model.Admin.Admin.findOne({
            attributes: { exclude: ['delete_time','roleId']},
            include: {
                model: this.ctx.app.model.Admin.Role,
                include: {
                    model: this.ctx.app.model.Admin.Permission,                    
                },
                where:{
                    status:this.ctx.app.enums.status.normal.value
                },
            },
            where:{
                id:2,
                // name:login_user.name,
                // password:login_user.password,
                status:this.ctx.app.enums.status.normal.value
            }
        });
        if(this.ctx.app.utils.validator.isNull(admin)){
            return router;
        } 
        if(this.ctx.app.utils.validator.isNull(admin.role)){
            return router;
        }        
        const permissions =admin.role.permissions;
        if(this.ctx.app.utils.validator.isNull(permissions)){
            return router;
        }
        //构建路由菜单      
        const menu = permissions.filter(item => item.type == this.ctx.app.enums.permission_type.menu.value && item.show == this.ctx.app.enums.show_status.show.value);
        var meta ={};
        var urls =['http','https','.com','.cn','www.'];
        for (const item of menu){
            meta ={
                'title': item.name,
                // 'target': '_blank',
                'show': item.show ==true ? true : false
            };
            for(const s in urls){
                if(item.path.indexOf(s)!= -1){
                    meta.target ='_blank';
                    continue;
                }else if(item.redirect.indexOf(s)!= -1){
                    meta.target ='_blank';
                    continue;
                }
            }
            // if(urls.indexOf(item.path)!=-1){
            //     meta.target ='_blank';
            // }else if(urls.indexOf(item.redirect)!=-1){
            //     meta.target ='_blank';
            // }
            item.setDataValue( 'name', item.key );
            item.setDataValue( 'meta', meta );
            item.setDataValue( 'parentId', item.pid);
        }        
        return menu;        
    }

    async menu2(){
        var router =[];
        const admin = await this.ctx.model.Admin.Admin.findOne({
            attributes: { exclude: ['delete_time','roleId']},
            include: {
                model: this.ctx.app.model.Admin.Role,
                include: {
                    model: this.ctx.app.model.Admin.Permission,                    
                },
                where:{
                    status:this.ctx.app.enums.status.normal.value
                },
            },
            where:{
                id:2,
                // name:login_user.name,
                // password:login_user.password,
                status:this.ctx.app.enums.status.normal.value
            }
        });
        if(this.ctx.app.utils.validator.isNull(admin)){
            return router;
        } 
        if(this.ctx.app.utils.validator.isNull(admin.role)){
            return router;
        }        
        const permissions =admin.role.permissions;
        if(this.ctx.app.utils.validator.isNull(permissions)){
            return router;
        }
        //构建路由菜单      
        const menu = permissions.filter(item => item.type == this.ctx.app.enums.permission_type.menu.value);
        var meta ={};
        var data =await this.menuNode(menu,0);
        console.log(666,data);
        var root={         
            key:'/',
            title:'首页',
            component: "BasicLayout",
            redirect: "/dashboard/workplace",
            children: data   
        }   
        router.push(root);
        return router;        
    }

    async menuNode(permissions,pid){
        if(this.ctx.app.utils.validator.isNull(pid)){
            pid =0;
        }
        var data =[];
        var menu ={};
        var obj =permissions.filter(item => item.pid == pid && item.type == this.ctx.app.enums.permission_type.menu.value);
        for (const item of obj){
            menu ={};
            menu.id =item.id;
            menu.pid =item.pid;
            menu.parentId =item.pid;
            menu.title =item.name;
            menu.key =item.key;
            menu.icon =item.icon;
            menu.path =item.path;
            menu.redirect =item.redirect;
            menu.children=await this.menuNode(permissions,item.id);
            data.push(menu);
        }
        return data;
    }

    

    
  
}

module.exports = HomeService;